/*
 * Copyright (c) 2010. Dylan Schell.
 */

package nl.xs4all.dylanschell.deckprinter.services;

import com.google.inject.Inject;
import com.google.inject.Singleton;
import nl.xs4all.dylanschell.deckprinter.model.CardInDeck;
import nl.xs4all.dylanschell.deckprinter.model.DeckDescriptor;
import org.octgn.deck.ObjectFactory;
import org.octgn.types.CTCard;
import org.octgn.types.CTDeck;
import org.octgn.types.CTSection;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

@Singleton
public class DeckServiceImpl implements DeckService
{
    private final List<DeckDescriptor> allDecks = new ArrayList<DeckDescriptor>();
    private final DeckPrinterConfig config;
    private final Marshaller marshaller;

    @Inject
    public DeckServiceImpl(DeckPrinterConfig config) throws JAXBException
    {
        this.config = config;
        JAXBContext ctx = JAXBContext.newInstance(
                "org.octgn.cardset:org.octgn.deck:org.octgn.types:org.openxmlformats.schemas._package._2006.relationships");
        marshaller = ctx.createMarshaller();
    }

    public void registerDeck(DeckDescriptor deck)
    {
        allDecks.add(deck);
    }

    public List<DeckDescriptor> getAllDecks()
    {
        return allDecks;
    }

    public File saveDeck(DeckDescriptor deck)
    {
        File deckFolder = config.getDeckFolder();
        CTDeck ctDeck = new CTDeck();
        for (String section : deck.getSections())
        {
            CTSection ctSection = new CTSection();
            ctSection.setName(section);
            ctDeck.getSection().add(ctSection);
            for (CardInDeck card : deck.getCardsInSection(section))
            {
                CTCard ctCard = new CTCard();
                ctSection.getCard().add(ctCard);
                ctCard.setQty(card.getQuantity());
                ctCard.setValue(card.getName());
                if (card.getId() != null)
                {
                    ctCard.setId(card.getId().toString());
                }
                //CardInDeck c = new CardInDeck(card.getName(), 1, card.getId());
            }
        }
        ctDeck.setGame("A6C8D2E8-7CD8-11DD-8F94-E62B56D89593");
        String name = deck.getName();
        int dot = name.lastIndexOf(".");
        if (dot > 0)
        {
            name = name.substring(0, dot);
        }
        name += ".o8d";
        File deckFile = new File(deckFolder, name);
        try
        {
            JAXBElement<CTDeck> element = new ObjectFactory().createDeck(ctDeck);
            marshaller.marshal(element, deckFile);
        } catch (JAXBException e)
        {
            e.printStackTrace();
        }
        return deckFile;
    }
}
